//
//  TestHomeViewController.m
//  copyrightTrading
//
//  Created by edz on 2020/10/14.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeRecommandViewController.h"
#import "HomeCategoryViewController.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "JXCategoryTitleView.h"
#import "PopView.h"
#import "TZImagePickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "SearchResultViewController.h"
//#import "VideoViewController.h"
@interface HomeViewController ()<JXCategoryListContainerViewDelegate, JXCategoryViewDelegate, PopViewDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate , UITextFieldDelegate>
@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) JXCategoryBaseView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

@property (nonatomic, assign) BOOL isNeedIndicatorPositionChangeItem;

@property (nonatomic, strong) JXCategoryTitleView *myCategoryTitleView;

//@property (nonatomic, strong) NSArray *commendList; // 轮播图数据
//@property (nonatomic, strong) NSArray *fashionListArray; // 最新发布
//@property (nonatomic, strong) NSArray *yingxiangList; // 影像馆
//@property (nonatomic, strong) NSArray *vipList; // VIP下载专区
//@property (nonatomic, strong) NSDictionary *adDic; // 广告

@property (nonatomic, strong) NSArray *navList;

@property (nonatomic, strong)NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) PopView *popView;
@property (nonatomic, copy) NSString*fileStringName;

@property (nonatomic, assign) BOOL isRequestSuccess;
@end

@implementation HomeViewController

- (void)tapImgChooseSourceType:(NSInteger)sourctType
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.maxImagesCount = 1;
    if (sourctType == 1) {
        imagePickerVc.allowPickingImage = YES;
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowTakePicture = YES;   // 在内部显示拍照片按
    } else {
        imagePickerVc.allowPickingImage = NO;
        imagePickerVc.allowPickingVideo = YES;
        imagePickerVc.allowTakeVideo = YES;   // 在内部显示拍视频按
    }
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    WeakSelf(self);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf.selectedPhotos removeAllObjects];
        [weakSelf.selectedAssets removeAllObjects];
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:@[photos[0]]];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:@[assets[0]]];
//        self.popView.img.image = photos[0];
        weakSelf.popView.contentLab.text = @"图片文件上传成功";
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark == 视频选择代理方法
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    // open this code to send video / 打开这段代码发送视频
    WeakSelf(self);
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
        weakSelf.fileStringName = outputPath;
//        weakSelf.popView.img.image = coverImage;
        weakSelf.popView.contentLab.text = @"视频文件上传成功";
        // NSData *data = [NSData dataWithContentsOfFile:outputPath];
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        // Export completed, send video here, send by outputPath or NSData
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
        
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
        
    }];
}

- (void)PopViewEnsureClickWithType:(PopViewType)type content:(nonnull NSString *)content
{
    NSLog(@"%ld",(long)type);
    SearchResultViewController *vc = [[SearchResultViewController alloc] init];
    vc.pageIndex = 1;
    if (type == KVideoType) {
        if (!self.selectedAssets.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.fileStringName} url:@"videoSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            vc.dataArray = dict[@"data"][@"search_list"];
            [self pushVc:vc];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:YES];
    } else if (type == KFaceType) {
        if (!self.selectedPhotos.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.selectedPhotos[0]} url:@"faceSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            vc.dataArray = dict[@"data"][@"search_list"];
            [self pushVc:vc];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:NO];
    } else if (type == KPictureType) {
        if (!self.selectedPhotos.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.selectedPhotos[0]} url:@"logoSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            vc.dataArray = dict[@"data"][@"search_list"];
            [self pushVc:vc];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:NO];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    YCShadowView *searchViewleft = [[YCShadowView alloc] init];
    searchViewleft.backgroundColor = RGB_VALUE(0x767680);
    searchViewleft.alpha = 0.33;
    [searchViewleft yc_cornerRadius:10 byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft];
    [self.view addSubview:searchViewleft];
    [searchViewleft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.height.mas_equalTo(36);
        make.top.offset(Height_StatusBar+5);
        make.width.mas_equalTo(106);
    }];
    
    // 为了让搜索按钮颜色突出
    UIView *searchView1 = [[UIView alloc] init];
    searchView1.layer.masksToBounds = YES;
    searchView1.layer.cornerRadius = 10;
    searchView1.clipsToBounds = YES;
    [self.view addSubview:searchView1];
    [searchView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.height.mas_equalTo(36);
        make.top.offset(Height_StatusBar+5);
    }];
    
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = RGB_VALUE(0x767680);
    searchView.layer.masksToBounds = YES;
    searchView.layer.cornerRadius = 10;
    searchView.alpha = 0.33;
    searchView.clipsToBounds = YES;
    [searchView1 addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(16);
//        make.right.offset(-16);
//        make.height.mas_equalTo(36);
//        make.top.offset(Height_StatusBar+5);
        make.edges.offset(0);
    }];
    
    UIButton *pictureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [pictureBtn setImage:[UIImage imageNamed:@"pictureSearch"] forState:UIControlStateNormal];
    [pictureBtn addTarget:self action:@selector(pictureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:pictureBtn];
    [pictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UIButton *taibiaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [taibiaoBtn setImage:[UIImage imageNamed:@"taibiaoSerach"] forState:UIControlStateNormal];
    [taibiaoBtn addTarget:self action:@selector(taibiaoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:taibiaoBtn];
    [taibiaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pictureBtn.mas_right).offset(7);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UIButton *videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBtn setImage:[UIImage imageNamed:@"videoSearch"] forState:UIControlStateNormal];
    [videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:videoBtn];
    [videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(taibiaoBtn.mas_right).offset(7);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UITextField *searchTextF = [[UITextField alloc] init];
    searchTextF.placeholder = @"输入内容来搜索";
    searchTextF.delegate = self;
    searchTextF.font = JSS_MEDIUM_FONT_3;
    searchTextF.returnKeyType = UIReturnKeySearch;
    [searchView1 addSubview:searchTextF];
    [searchTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchViewleft.mas_right).offset(10);
        make.right.offset(-35);
        make.centerY.offset(0);
        make.height.mas_equalTo(searchView.mas_height);
    }];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setImage:[UIImage imageNamed:@"popViewSearch"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView1 addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-12);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"sort" parameters:@{} done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        self.commendList = responseObject[@"data"][@"commend_list"];
//        self.yingxiangList = responseObject[@"data"][@"yingxiang_list"];
//        self.vipList = responseObject[@"data"][@"vip_list"][@"list"];
//        self.adDic = responseObject[@"data"][@"adv"];
//        self.fashionListArray = responseObject[@"data"][@"new_list"];
        if (self.navList.count) {
            return;
        }
        self.navList = responseObject[@"data"][@"nav_list"];
        NSMutableArray *titleList = [NSMutableArray array];
        [titleList addObject:@"推荐"];
        for (NSDictionary *menu in responseObject[@"data"][@"nav_list"]) {
            [titleList addObject:menu[@"title"]];
        }
        self.titles = [titleList copy];
        
        self.myCategoryTitleView.titles = self.titles;
        [self.view addSubview:self.listContainerView];
        self.categoryView.listContainer = self.listContainerView;
        self.categoryView.delegate = self;
        [self.view addSubview:self.categoryView];
        
        self.myCategoryTitleView.titleColorGradientEnabled = YES;
        self.myCategoryTitleView.titleSelectedColor = RGB_VALUE(0xFFFFFF);
        self.myCategoryTitleView.titleColor = RGB_VALUE(0x636363);
        self.myCategoryTitleView.titleSelectedFont = JSS_MEDIUM_FONT_5;
        self.myCategoryTitleView.titleFont = JSS_MEDIUM_FONT_3;
        JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
        backgroundView.indicatorHeight = JXCategoryViewAutomaticDimension;
        backgroundView.indicatorCornerRadius = 0;
        backgroundView.indicatorHeight = 28;
        backgroundView.tintColor = RGB_VALUE(0xDC0000);
        self.myCategoryTitleView.indicators = @[backgroundView];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
    
    [[HWNetworkReachabilityManager shareManager] monitorNetworkStatus];
    
//    [self observeNetWork];
}

- (void)observeNetWork {
    
    // 开启网络监听
    [[HWNetworkReachabilityManager shareManager] monitorNetworkStatus];
    
    WeakSelf(self);
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable || status == AFNetworkReachabilityStatusUnknown) {
            //无网络链接
            NSLog(@"==无网络链接");

        } else {
            //网络链接成功
            
            NSLog(@"==网络链接成功");
            
            [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"sort" parameters:@{} done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
                if (weakSelf.navList.count) {
                    return;
                }
                weakSelf.navList = responseObject[@"data"][@"nav_list"];
                NSMutableArray *titleList = [NSMutableArray array];
                [titleList addObject:@"推荐"];
                for (NSDictionary *menu in responseObject[@"data"][@"nav_list"]) {
                    [titleList addObject:menu[@"title"]];
                }
                weakSelf.titles = [titleList copy];
                
                weakSelf.myCategoryTitleView.titles = weakSelf.titles;
                [weakSelf.view addSubview:weakSelf.listContainerView];
                weakSelf.categoryView.listContainer = weakSelf.listContainerView;
                weakSelf.categoryView.delegate = self;
                [weakSelf.view addSubview:weakSelf.categoryView];
                
                weakSelf.myCategoryTitleView.titleColorGradientEnabled = YES;
                weakSelf.myCategoryTitleView.titleSelectedColor = RGB_VALUE(0xFFFFFF);
                weakSelf.myCategoryTitleView.titleColor = RGB_VALUE(0x636363);
                weakSelf.myCategoryTitleView.titleSelectedFont = JSS_MEDIUM_FONT_5;
                weakSelf.myCategoryTitleView.titleFont = JSS_MEDIUM_FONT_3;
                JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
                backgroundView.indicatorHeight = JXCategoryViewAutomaticDimension;
                backgroundView.indicatorCornerRadius = 0;
                backgroundView.indicatorHeight = 28;
                backgroundView.tintColor = RGB_VALUE(0xDC0000);
                weakSelf.myCategoryTitleView.indicators = @[backgroundView];
            } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                
            }];
        }
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"%@",textField.text);
    if (NULLString(textField.text)) {
        [self showMessage:@"搜索内容不能为空"];
        return NO;
    }
    NSDictionary *paramDic = @{
        @"type":@"",
        @"sort_id":@"",
        @"keyword":textField.text,
        @"page":@(1),
        @"limit":@(10),
        @"is_commend":@(0)
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"material" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        SearchResultViewController *vc = [[SearchResultViewController alloc] init];
        vc.dataArray = responseObject[@"data"][@"list"][@"list"];
        vc.pageIndex = 1;
        [self pushVc:vc];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
    return YES;
}

// 视频搜索
- (void)videoBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KVideoType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}

// 人脸搜索
- (void)taibiaoBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KFaceType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}
// 台标搜索
- (void)pictureBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KPictureType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}

- (void)searchBtnClick
{
    SearchResultViewController *vc = [[SearchResultViewController alloc] init];
    [self pushVc:vc];
}

- (JXCategoryTitleView *)myCategoryTitleView {
    return (JXCategoryTitleView *)self.categoryView;
}

- (JXCategoryBaseView *)preferredCategoryView {
    return [[JXCategoryTitleView alloc] init];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    self.categoryView.frame = CGRectMake(0, Height_StatusBar + 41, self.view.bounds.size.width, [self preferredCategoryViewHeight]);
    self.listContainerView.frame = CGRectMake(0, [self preferredCategoryViewHeight]+Height_StatusBar+41, self.view.bounds.size.width, self.view.bounds.size.height - [self preferredCategoryViewHeight]-Height_StatusBar-41);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //处于第一个item的时候，才允许屏幕边缘手势返回
    self.navigationController.interactivePopGestureRecognizer.enabled = (self.categoryView.selectedIndex == 0);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

- (CGFloat)preferredCategoryViewHeight {
    return 50;
}

- (JXCategoryBaseView *)categoryView {
    if (_categoryView == nil) {
        _categoryView = [self preferredCategoryView];
    }
    return _categoryView;
}

- (JXCategoryListContainerView *)listContainerView {
    if (_listContainerView == nil) {
        _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    }
    return _listContainerView;
}

#pragma mark - JXCategoryListContainerViewDelegate

-(id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 0) {
        HomeRecommandViewController *list = [[HomeRecommandViewController alloc] init];
//        list.commendList = self.commendList;
//        list.yingxiangList = self.yingxiangList;
//        list.vipList = self.vipList;
//        list.fashionListArray = self.fashionListArray;
//        list.adDic = self.adDic;
        return list;
    }
    HomeCategoryViewController *list = [[HomeCategoryViewController alloc] init];
    list.navDic = self.navList[index-1];
    return list;
}

-(NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.titles.count;
}

#pragma mark - JXCategoryViewDelegate

- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    //侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}
@end
